# -*- coding: utf-8 -*-
"""
Author:duan
Date: 2021/3/4 23:09
"""
import time
import pika

credentials = pika.PlainCredentials('guest', 'guest')
params = pika.ConnectionParameters(host='127.0.0.1', credentials=credentials)
connection = pika.BlockingConnection(params)
channel = connection.channel()

channel.exchange_declare(exchange='ex2', exchange_type='fanout')
# 声明一个名为ex1的交换器，发布类型为集体分发

result = channel.queue_declare(queue='', exclusive=True)
# 这里不定义名字，通过exclusive=True生成一个名字不重复的队列

queue_name = result.method.queue
# 获取队列名

channel.queue_bind(queue_name, exchange='ex2')


# 绑定队列名和ex1交换器
def callback(ch, method, properites, body):
    print(" [x] Received %r" % body)
    time.sleep(10)
    print(" msg handle done: %r" % body)


channel.basic_consume(queue=queue_name,
                      on_message_callback=callback,
                      auto_ack=True)

# 使用随机生成的队列名在ex2交换器下接收消息
print('queue:{} start...'.format(queue_name))
channel.start_consuming()
